const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const config = require('./config/config');
const { logger } = require('./utils/logger');
const browser = require('./services/browser');
const rateLimiter = require('./middleware/rateLimiter');
const errorHandler = require('./middleware/errorHandler');
const automationRoutes = require('./routes/automation');

const app = express();

// 安全中间件
app.use(helmet());
app.use(cors());

// 请求解析
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 频率限制
app.use(rateLimiter);

// 请求日志中间件
app.use((req, res, next) => {
  logger.info(`收到请求`, {
    method: req.method,
    url: req.url,
    ip: req.ip
  });
  next();
});

// API路由
app.use('/api/automation', automationRoutes);

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 根路径 获取接口列表
app.get('/', (req, res) => {
  res.json({
    name: 'Browser Automation Server',
    version: '2.0.0',
    description: '支持Puppeteer和Playwright双引擎的浏览器自动化API服务器',
    features: [
      '网页截图',
      '页面内容获取', 
      '表单自动填写',
      '元素点击操作',
      '豆包AI图片生成（仅Puppeteer）',
      '服务器状态监控'
    ],
    endpoints: {
      screenshot: {
        method: 'POST',
        path: '/api/automation/screenshot',
        description: '网页截图',
        params: ['url', 'engine(可选)', '其他截图选项']
      },
      content: {
        method: 'POST', 
        path: '/api/automation/content',
        description: '获取页面内容',
        params: ['url', 'engine(可选)', '其他内容获取选项']
      },
      form: {
        method: 'POST',
        path: '/api/automation/form', 
        description: '填写表单',
        params: ['url', 'formData', 'engine(可选)', '其他表单选项']
      },
      click: {
        method: 'POST',
        path: '/api/automation/click',
        description: '点击页面元素',
        params: ['url', 'selector', 'engine(可选)', '其他点击选项']
      },
      doubaoImages: {
        method: 'POST',
        path: '/api/automation/doubao-images',
        description: '豆包AI图片生成（仅支持Puppeteer）',
        params: ['prompt', 'engine(可选)', '其他生成选项']
      },
      status: {
        method: 'GET',
        path: '/api/automation/status',
        description: '获取服务器和浏览器状态',
        params: []
      }
    },
    engines: ['puppeteer', 'playwright'],
    health: '/health'
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    error: '接口不存在'
  });
});

// 错误处理
app.use(errorHandler);

// 启动服务器
async function startServer() {
  try {
    // 初始化浏览器
    await browser.init();
    
    // 启动HTTP服务器
    const server = app.listen(config.server.port, () => {
      logger.info(`服务器启动成功，运行地址: http://localhost:${config.server.port}`);
      logger.info(`环境: ${config.server.env}`);
    });

    // 优雅关闭处理
    const gracefulShutdown = async (signal) => {
      logger.info(`收到 ${signal} 信号，开始优雅关闭`);
      
      server.close(async () => {
        logger.info('HTTP服务器已关闭');
        
        try {
          await browser.destroy();
          logger.info('浏览器已销毁');
          process.exit(0);
        } catch (error) {
          logger.error(`关闭浏览器失败: ${error.message}`);
          process.exit(1);
        }
      });
    };

    // 注册信号处理器
    ['SIGTERM', 'SIGINT'].forEach(signal => {
      process.on(signal, () => gracefulShutdown(signal));
    });
    
    // 未捕获异常处理
    process.on('uncaughtException', (error) => {
      logger.error('未捕获异常:', error);
      process.exit(1);
    });
    
    process.on('unhandledRejection', (reason, promise) => {
      logger.error('未处理的Promise拒绝:', { reason, promise });
      process.exit(1);
    });

  } catch (error) {
    logger.error(`服务器启动失败: ${error.message}`);
    process.exit(1);
  }
}

// 启动应用
if (require.main === module) {
  startServer();
}

module.exports = app;